<template>
  <div>
    <VForm
      ref="vformComponents"
      :form="formData.form"
      :options="formData.options"
      :rules="formData.rules"
      :labelWidth="formData.labelWidth"
      :rowspan="rowspan"
      @changeAddress="changeAddress"
      @changeGdArea="changeGdArea"
      @toLoadMethods="toLoadMethods"

    ></VForm>

    <div class="formTitle-root">
      <div class="form-title-p">受理派单信息</div>
    </div>


    <VForm
      ref="vformComponents1"
      :form="formData1.form"
      :options="formData1.options"
      :rules="formData1.rules"
      :labelWidth="formData1.labelWidth"
      :rowspan="rowspan"
      @toLoadMethods="toLoadMethods"
    ></VForm>

    <div class="formTitle-root">
      <div class="form-title-p">整改处置信息</div>
    </div>
    <div>
      <v-table
        v-if="tableMainHeight>0"
        :table-columns="tableColumns"
        :table-data="tableData"
        :loading="loading"
        :is-index="false"
        :isSelection="false"
        :isDynamicCol="false"
        ref="table"

        :maxHeight="tableMainHeight">

        <template #handleResultState="scope">
          {{getResultStateValue(scope.row.handleResultState, handleResultStateOptions)}}
        </template>



        <template #sceneFile="scope">
          <div v-if="checkFileShow(scope.row.sceneFile)" style="text-align: center">
            <div v-for="(item,index) in JSON.parse(scope.row.sceneFile)"  >
              <el-link type="primary"  :underline="false" @click="downFile(item)">{{item.name}}</el-link>
            </div>
          </div>
          <div v-else></div>
        </template>

        <template #handleImg="scope">
          <div v-if="checkFileShow(scope.row.handleImg)" style="text-align: center">
            <div v-for="(item,index) in JSON.parse(scope.row.handleImg)"  >

              <el-image style="height: 100px" :src="buildImg(item)"/>
            </div>
          </div>
          <div v-else></div>
        </template>

        <template #handleReport="scope">
          <div v-if="checkFileShow(scope.row.handleReport)" style="text-align: center">
            <div v-for="(item,index) in JSON.parse(scope.row.handleReport)"  >
              <el-link type="primary"  :underline="false" @click="downFile(item)">{{item.name}}</el-link>
            </div>
          </div>
          <div v-else></div>
        </template>



      </v-table>

    </div>
  </div>
</template>

<script>
  import { riskHazardDetail,
    riskHazardHandle,
    riskHazardAdd } from '@/api/risk/riskHazard'
  import { treeDataChild} from '@/api/risk/treeData'
  import { alarmFacilityList} from '@/api/alarm/facility'
  import VForm from "@/components/VForm/index";
  import VTable from '@/components/VTable/index'
  export default {
    components: {
      VTable,VForm,
    },
    props: {
      width: {
        type: String,
        default: "70%",
      },
      title: {
        type: String,
        default: "详情",
      },
      id:{},
      openType:{
        type:String,
        default:"add"
      },
      dialogVisible: {
        type: Boolean,
        default: false
      }
    },
    watch: {
      'width': {
        handler(newVal, oldVal) {
          console.log('newVal===',newVal, oldVal)
          let w = this.width.split('%')[0]
          if(w>=60){
            this.rowspan = 2
          }else{
            this.rowspan = 1
          }
        },
        deep: true,
        immediate: true
      },
      'bClassifyOptions':{
        handler(newVal, oldVal) {
          console.log('.....',newVal);
          this.formData.options.forEach(t=>{
            if(t.key=='bclassify'){
              t.option.data = newVal
            }
          })
        },
        deep: true,
        immediate: true
      },
      'sClassifyOptions':{
        handler(newVal, oldVal) {
          this.formData.options.forEach(t=>{
            if(t.key=='sclassify'){
              t.option.data = newVal
            }
          })
        },
        deep: true,
        immediate: true
      },
      'categoryOptions':{
        handler(newVal, oldVal) {
          this.formData.options.forEach(t=>{
            if(t.key=='category'){
              t.option.data = newVal
            }
          })
        },
        deep: true,
        immediate: true
      },
      'gradeOptions':{
        handler(newVal, oldVal) {
          this.formData.options.forEach(t=>{
            if(t.key=='grade'){
              t.option.data = newVal
            }
          })
        },
        deep: true,
        immediate: true
      },
      'stateOptions':{
        handler(newVal, oldVal) {
          this.formData.options.forEach(t=>{
            if(t.key=='state'){
              t.option.data = newVal
            }
          })
        },
        deep: true,
        immediate: true
      },
      'facilityOptions':{
        handler(newVal, oldVal) {
          this.formData.options.forEach(t=>{
            if(t.key=='facilityId'){
              t.option.data = newVal
            }
          })
        },
        deep: true,
        immediate: true
      },
      dialogVisible:{
        handler(newVal, oldVal) {
          if(newVal){
            console.log("监测指===",newVal)
            this.getData()
          }
        },
        deep: true,
        immediate: true
      }
    },
    computed: {
      isVisible: {
        get() {
          return this.dialogVisible
        },
        set() {
          this.close()
        }
      }
    },
    data() {
      return {
        rowspan:1,
        dict:{},
        formData: {
          form: {
            flagCode:"",
            reportTime:"",
            name:"",
            bclassify:"",

            sclassify:"",
            category:"",
            address:"",
            memo:"",
            grade:"",
            state:"",
            reportName:"",
            reportContact:"",


            objClassify:"",
            objName:"",
            lon:"",
            lat:"",
            provinceCode:"",
            cityCode:"",
            countyCode:"",
            areaCode:"",
            updateTime:"",
            updateBy:"",

            reportUnit:"",
            img:[],
            discoveryTime:"",
            mapData:null,
            facilityId:'',
            facilityName:'',
          },
          options: [

            {
              title: "隐患上报时间",
              key: "reportTime",
              type: "date",
              disabled: true
            },
            {
              title: "隐患名称",
              key: "name",
              type: "text",
              disabled: true
            },
            {
              title: "隐患大类",
              key: "bclassify",
              type: "select",
              multiple:false,
              event:'changeBclassify',
              option: {
                data: this.bClassifyOptions,
                props: {
                  key: "id", // 指定key对应data的字段
                  label: "label", // 指定label对应data的字段
                  value: "name", // 指定value对应data的字段
                },
              },
              disabled: true
            },
            {
              title: "隐患细类",
              key: "sclassify",
              type: "select",
              multiple:false,

              option: {
                data: this.sClassifyOptions,
                props: {
                  key: "id", // 指定key对应data的字段
                  label: "label", // 指定label对应data的字段
                  value: "name", // 指定value对应data的字段
                },
              },
              disabled: true
            },


            {
              title: "三级类别",
              key: "category",
              type: "select",
              multiple:false,
              option: {
                data: this.categoryOptions,
                props: {
                  key: "id", // 指定key对应data的字段
                  label: "label", // 指定label对应data的字段
                  value: "name", // 指定value对应data的字段
                },
              },
              disabled: true
            },

            {
              title: "设施名称",
              key: "facilityId",
              type: "select",
              multiple:false,
              event:'changeFacilityName',
              option: {
                data: this.facilityOptions,
                props: {
                  key: "id", // 指定key对应data的字段
                  label: "label", // 指定label对应data的字段
                  value: "name", // 指定value对应data的字段
                },
              },
              disabled: true
            },

            {
              title: "隐患等级",
              key: "grade",
              type: "select",
              multiple:false,
              option: {
                data: this.gradeOptions,
                props: {
                  key: "id", // 指定key对应data的字段
                  label: "label", // 指定label对应data的字段
                  value: "value", // 指定value对应data的字段
                },
              },
              disabled: true
            },
            {
              title: "上报单位",
              key: "reportUnit",
              type: "text",
              disabled: true
            },
            {
              title: "上报人",
              key: "reportName",
              type: "text",
              disabled: true
            },
            {
              title: "上报人电话",
              key: "reportContact",
              type: "text",
              disabled: true
            },
            {
              title: "发现时间",
              key: "discoveryTime",
              type: "date",
              disabled: true
            },
            {
              title: "隐患地址",
              type:'mapPosition',
              key:'mapData',

            },
            {
              title: "现场照片",
              key: "img",
              type: "file",
              fileType: "image",
              listType: "picture-card",
              uploadTextTip: "",
              columnWidth: 'w100max',
              disabled: true
            },
            {
              title: "隐患描述",
              key: "memo",
              type: "textarea",
              columnWidth: 'w100max',
              disabled: true
            }
          ],
          rules: {

          },
          labelWidth: "140px",
        },
        formData1: {
          form: {

            handleUnit:"",
            handleName:"",
            acceptTime:"",
            handleNameContact:"",
            requireCompleteTime:"",

          },
          options: [

            {
              title: "风险隐患处置单位",
              key: "handleUnit",
              type: "text",
              disabled: true
            },
            {
              title: "风险隐患受理时间",
              key: "acceptTime",
              type: "date",
              disabled: true
            },
            {
              title: "风险隐患处置负责人",
              key: "handleName",
              type: "text",
              disabled: true
            },
            {
              title: "要求整改完成时间",
              key: "requireCompleteTime",
              type: "date",
              disabled: true
            },

            {
              title: "负责人联系电话",
              key: "handleNameContact",
              type: "text",
              disabled: true
            },
          ],
          rules: {
          },
          labelWidth: "140px",
        },

        tableColumns:[
          {
            prop: 'handleTime',
            label: '风险隐患处置完成时间',
            minWidth: '150',
            slotname: 'handleTime',
            options: {}
          },
          {
            prop: 'handleMemo',
            label: '风险隐患处理描述',
            minWidth: '250',
            slotname: 'handleMemo',
            options: {}
          },

          {
            prop: 'sceneFile',
            label: '风险隐患现场文件',
            minWidth: '150',
            slotname: 'sceneFile',
            options: {}
          },
          {
            prop: 'handleImg',
            label: '风险隐患处置图片',
            minWidth: '150',
            slotname: 'handleImg',
            options: {}
          },
          {
            prop: 'handleReport',
            label: '风险隐患处置报告',
            minWidth: '150',
            slotname: 'handleReport',
            options: {}
          },

          {
            prop: 'handleResultState',
            label: '整改结果',
            minWidth: '100',
            slotname: 'handleResultState',
            option: {
              data: this.handleResultStateOptions,
              props: {
                key: "id", // 指定key对应data的字段
                label: "label", // 指定label对应data的字段
                value: "value", // 指定value对应data的字段
              },
            },
          },
        ],
        tableData:[],
        selection: [],
        loading:false,
        tableMainHeight: 0,
        // 字典
        bClassifyOptions:[],
        sClassifyOptions:[],
        categoryOptions:[],
        gradeOptions:[],
        stateOptions:[],
        handleResultStateOptions:[],
        facilityOptions:[]
      };



    },
    methods: {

      buildImg(obj){
        return process.env.VUE_APP_BASE_API + 'file/api/download/'+obj.fileId;
      },
      //下载文件
      downFile(obj){
        // window.open( process.env.VUE_APP_BASE_API + 'file/api/download/'+obj.fileId);

        const link = document.createElement('a');
        link.href = process.env.VUE_APP_BASE_API + 'file/api/download/'+obj.fileId;
        link.setAttribute('download', obj.fileName);
        link.click();
      },

      // 判断是否存在上传附件
      checkFileShow(value){
        if (value == null || value == '' || value=='null') {
          return false;
        }
        let f = JSON.parse(value)
        return f.length > 0 ? true : false
      },

      getResultStateValue(value,list){
        let item =list.find(t=>t.value == value);
        if(item!=undefined){
          return item.label;
        }
        return;
      },



      toLoadMethods(methods){
        this[methods]();
      },

      changeFacilityName(){
        var label = this.facilityOptions.find(t=>t.name==this.formData.form.facilityId).label;
        this.formData.form.facilityName=label;

      },

      changeBclassify(){
        this.formData.form.sclassify='';
        this.sClassifyOptions=[];

        this.formData.form.facilityId='';
        this.formData.form.facilityName='';
        this.facilityOptions=[];

        this.sendBclassifyData();
      },

      async sendBclassifyData(){
        let queryData ={}
        queryData.name='hazardBClassify';
        queryData.code =this.formData.form.bclassify;
        let res =await treeDataChild(queryData);
        if(res.code==200) {
          let that = this
          res.data.forEach(function (item,index){
            var one ={}
            one.label= item.label;
            one.name=item.code;
            one.modeType=item.modeType;
            that.sClassifyOptions.push(one);
          })

          if(this.formData.form.sclassify!=''){
            this.sendFacilityData();
          }
        }

      },

      changeSclassify(){
        this.formData.form.category='';
        this.categoryOptions=[]
        this.sendCategoryData();

        this.formData.form.facilityId='';
        this.formData.form.facilityName='';
        this.facilityOptions=[];
        this.sendFacilityData();
      },

      async sendCategoryData(){
        let queryData ={}
        queryData.name='hazardSClassify';
        queryData.code =this.formData.form.sclassify;
        let res =await treeDataChild(queryData);
        if(res.code==200) {
          let that = this
          res.data.forEach(function (item,index){
            var one ={}
            one.label= item.label;
            one.name=item.code;
            that.categoryOptions.push(one);
          })
        }
      },

      async sendFacilityData(){
        let queryData ={}
        let modeType = this.sClassifyOptions.find(t=>t.name==this.formData.form.sclassify).modeType;

        queryData.modeType="ALARM_"+modeType;
        let res =await alarmFacilityList(queryData);
        if(res.code==200) {
          let that = this
          res.data.forEach(function (item,index){
            var one ={}
            one.label=item.name ;
            one.name=item.id;
            that.facilityOptions.push(one);
          })

        }
      },
      getCountySubIndex(cityCode){
        // 中山、东莞截取10位
        let filterList = ['442000000000','441900000000']
        if(filterList.findIndex(t=>t==cityCode)>-1){
          return 10;
        }
        return 6;
      },
      positionSubmitFormat(){

        let mapData = this.formData.form.mapData
        console.log(">>>");
        console.log(mapData);
        if(mapData){
          this.formData.form.lon = mapData.gpsX
          this.formData.form.lat = mapData.gpsY
          this.formData.form.address = mapData.address
          this.formData.form.areaCode = mapData.towncode
          if(mapData.towncode){
            this.formData.form.provinceCode = mapData.towncode.substr(0,2).padEnd(12,'0')
            this.formData.form.cityCode = mapData.towncode.substr(0,4).padEnd(12,'0')
            let subIndex = this.getCountySubIndex(this.formData.form.cityCode)
            this.formData.form.countyCode = mapData.towncode.substr(0,subIndex).padEnd(12,'0')
          }
        }
      },
      positionLoadFormat(){
        let form = this.formData.form
        let mapData = {}


        mapData.address = form.address
        mapData.gpsX = parseFloat(form.lon)
        mapData.gpsY = parseFloat(form.lat)
        mapData.towncode = form.areaCode
        this.formData.form.mapData = mapData




        console.log("mpap",mapData)
      },


      submitFormat(){


      },
      loadFormat(){

        if(this.formData.form.img!=null && this.formData.form.img!='' && this.formData.form.img!='null'){
          this.formData.form.img = JSON.parse( this.formData.form.img ).map(item=>{
            return{
              name:item.name,
              url: process.env.VUE_APP_BASE_API + 'file/api/download/'+item.fileId,
              uid: item.uuid,
              fileId: item.fileId,
            }
          })
        }else {
          this.formData.form.img = []
        }

      },
      getCheckBoxData(value,option,type){
        if(type=="submit"){
          if(value.length==0){
            return null
          }
          let temp = [];
          value.forEach(t=>{
            let item = option.find(x=> x.label == t)
            if(item!=undefined){
              temp.push(item.value)
            }
          })
          return temp.join(",")
        }else {
          if(!value){
            return []
          }else {
            let data = value.split(",")
            let temp = []
            data.forEach(t=>{
              let item = option.find(x=> x.value == t)
              if(item!=undefined){
                temp.push(item.label)
              }
            })
            return temp
          }
        }
      },

      cancel(){
        this.close()
      },
      handleClose(done) {
        done()
        this.close()
      },
      closeSuccess(){
        this.$refs.vformComponents.$refs.form.resetFields();
        this.$refs.vformComponents1.$refs.form.resetFields();

        this.$emit('success')
        this.facilityOptions=[];
        this.categoryOptions=[];

      },
      close(){
        this.$refs.vformComponents.$refs.form.resetFields();
        this.$refs.vformComponents.$refs.mapPosition[0].reloadMap();
        this.$refs.vformComponents1.$refs.form.resetFields();

        this.$emit('close')
        this.facilityOptions=[];
        this.categoryOptions=[];
      },
      getData(){

        // 获取字典值
        this.bClassifyOptions = []
        this.$commonJs.filterDataDict("hazardBClassify",this.bClassifyOptions )

        this.sClassifyOptions = []
        //this.$commonJs.filterDataDict("hazardSClassify",this.sClassifyOptions )


        this.categoryOptions = []
        this.$commonJs.filterDataDict("hazardCategory",this.categoryOptions )

        this.gradeOptions = []
        this.$commonJs.filterDataDict("patrolHazardLevel",this.gradeOptions )

        this.stateOptions = []
        this.$commonJs.filterDataDict("hazardDealState",this.stateOptions )

        this.handleResultStateOptions =[{id:0,label:'通过',value:'Y'},{id:1,label:'不通过',value:'N'}]

        if(this.openType!="add"){
          riskHazardDetail(this.id).then(res=>{
            if(res.code==200){
              this.formData.form = res.data


              this.formData1.form.handleUnit = res.data.handleUnit;
              this.formData1.form.handleName = res.data.handleName;
              this.formData1.form.acceptTime = res.data.acceptTime;
              this.formData1.form.handleNameContact = res.data.handleNameContact;
              this.formData1.form.requireCompleteTime = res.data.requireCompleteTime;

              this.tableData = res.data.recordList
              this.sendBclassifyData();
              this.sendCategoryData();
              this.loadFormat()
              this.positionLoadFormat()


            }else{
              this.$message({
                message: this.$t('tips.systemException'),
                type: 'error'
              })
            }
          })
        }
      },

      changeAddress(data){
        // console.log(data)
        this.formData.form.mapData = data
        this.formData.form.areaCode = data.areaCode
      },
      changeGdArea(data){
        console.log(data)
      },
    },

    mounted(){
      this.tableMainHeight = document.getElementsByClassName('table-main')[0].clientHeight - 44 //减去顶部按钮列表的高度
    }


  };
</script>


<style lang="scss" scoped>
  @import "@/styles/element-variables.scss";
  .formTitle-root{
    padding: 10px 0;
    border-bottom: 1px solid #EFEFEF;
    font-size: 16px;
    position: relative;
    margin-bottom: 10px;
    .form-title-p{
      padding-left: 10px;
      border-left: 4px solid $--color-primary;
    }
  }
</style>

